package com.bingxue.edu.framework.job;

import com.alibaba.fastjson.JSON;
import com.bingxue.edu.management.system.model.entity.ScheduleJob;
import com.bingxue.edu.management.system.model.entity.ScheduleJobLog;
import com.bingxue.edu.management.system.service.ScheduleJobLogService;
import com.bingxue.edu.management.system.service.ScheduleJobService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author panbo
 * @since 2024/8/27
 */
@Slf4j
@Async
@Component
@AllArgsConstructor
public class SchedulerAsyncWorker {

    private final ScheduleJobService scheduleJobService;
    private final ScheduleJobLogService scheduleJobLogService;

    /**
     * 保存job执行日志
     *
     * @param scheduleJobLog
     */
    public void saveScheduleJobLog(ScheduleJobLog scheduleJobLog) {
        ScheduleJob scheduleJob = scheduleJobService.getById(scheduleJobLog.getJobId());
        if (scheduleJob == null) {
            log.error("获取定时任务`{}`异常；日志内容：{}", scheduleJobLog.getJobId(), JSON.toJSONString(scheduleJobLog));
        } else {
//            scheduleJobLog.setJobKey(scheduleJob.getJobKey());
            scheduleJobLog.setCron(scheduleJob.getCron());
            scheduleJobLog.setJobName(scheduleJob.getJobName());
            scheduleJobLog.setParamJson(scheduleJob.getParamJson());
            if (scheduleJob.getSaveLog()) {
                scheduleJobLogService.save(scheduleJobLog);
            } else {
                log.debug("定时任务`{}`关闭了日志记录，日志内容：{}", scheduleJobLog.getJobId(), JSON.toJSONString(scheduleJobLog));
            }
        }
    }

}
